package com.example.w.service.impl;

import com.example.w.common.exception.SystemException;
import com.example.w.common.pojo.User;
import com.example.w.common.util.Result;
import com.example.w.common.util.SaltUtils;
import com.example.w.common.util.Utils;
import com.example.w.dao.UserDao;
import com.example.w.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;


    @Override
    public Long register(User user) {
        if (!user.hasUsernameAndPasswd()) {
            throw new SystemException("用户名和密码不能为空");
        }
        //获取盐
        String salt = SaltUtils.getSalt(8);
        //使用盐加密密码，加上散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        //设置盐
        user.setSalt(salt);
        //保存用户信息
        userDao.registerUser(user);
        return null;
    }

    @Override
    public void login(User user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            System.out.println("登录成功");
        }catch (UnknownAccountException e) {
            throw new SystemException("用户名错误");
        }catch (IncorrectCredentialsException e) {
            throw new SystemException("密码错误");
        }
    }

    /**
    查询用户信息，仅查询登录信息
     */
    @Override
    public User selectUserByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    /**
     查询用户信息，包括角色信息
     */
    @Override
    public User selectRolesByUsername(String username) {
        return userDao.selectRolesByUsername(username);
    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

}
